﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Kiiro.Common.Utility;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class DisplayUser : BasePage
    {
        #region Properties
        private User user = new User ( );
        public new User User
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public PersonStatus PersonStatus
        {
            get { return ( PersonStatus ) v2PersonStatus; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public ActivityHistoryControl History
        {
            get { return ( ActivityHistoryControl ) v2ActivityHistoryControl; }
        }
        #endregion

        #region Page Events
        protected void Page_Load ( object sender, EventArgs e )
        {
            User = UserModel.GetOrCreateUser ( ItemId, SiteCollectionId, ServerRelativeUrl );
            ItemId = User.Id;

            CustomFields.ControlMode = SPControlMode.Display;
            CustomFields.EntityType = typeof ( User );

            if ( User != null )
            {
                if ( ItemId > 0 )
                    History.UserId = ItemId;

                litTitle.Text = !string.IsNullOrEmpty ( User.FullName ) ? "Display User - " + User.FullName : "Display User";
                PageTitle = User.FullName;

                PopulateForm ( );
                AddCommandButtons ( );

                if ( !IsPostBack )
                    PopulateProjectsListing ( );
            }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            base.OnPreRender ( e );

            if ( CurrentUser.IsAdministrator || ( CurrentUser.Id == User.Id && CurrentUser.Groups.Contains ( KiiroGroup.PortalMember ) ) )
            {
                PersonStatus.Visible = !User.IsADGroup;
                PersonStatus.User = User;
            }
            else
            {
                PersonStatus.Visible = false;
                liUserStatus.Visible = true;
                lblUserStatus.Text = SPHelpers.CheckTextForLinks ( User.StatusNote );
            }
        }

        #endregion

        #region Control Events
        protected void btnDelete_Click ( object sender, EventArgs e )
        {
            if ( PermissionBitsUsers [ 3 ] )
            {
                User.EditType = EditType.Deleted;
                User.ModifiedBy = CurrentUser;
                UserModel.Save ( User, SiteCollectionId, ServerRelativeUrl );
            }

            if ( User.IsValid ( ) )
                Response.Redirect ( String.Format ( "{0}/{1}", ServerRelativeUrl, Constants.PortalFileUrls.UserAll ) );
            else
            {
                ErrorsList errorsList = ( ErrorsList ) Page.Master.FindControl ( "v2ErrorsList" );
                errorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( User.EditTypeMessage ) );
            }
        }

        protected void btnEdit_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( User.IsADGroup ?
                String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.GroupEdit, User.SPUserId ) :
                String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserEdit, User.SPUserId ) );
        }
        #endregion

        #region Methods
        private void AddCommandButtons ( )
        {
            if ( CurrentUser.IsAdministrator && CurrentUser.Id != User.Id )
            {
                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = string.Format ( "Delete {0}", user.IsADGroup ? "Group" : "User" );
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                btnDelete.Click += new EventHandler ( btnDelete_Click );
                NavigationSub.Commands.Add ( btnDelete );
            }

            if ( CurrentUser.IsAdministrator || ( CurrentUser.Id == User.Id && CurrentUser.Groups.Contains( KiiroGroup.PortalMember ) ) )
            {
                LinkButton btnEdit = new LinkButton ( );
                btnEdit.Text = CurrentUser.Id == User.Id ? "Update your Profile" : string.Format ( "Edit {0}", user.IsADGroup ? "Group" : "User" );
                btnEdit.Attributes.Add ( "class", "icon-edit" );
                btnEdit.Click += new EventHandler ( btnEdit_Click );
                NavigationSub.Commands.Add ( btnEdit );
            }
        }

        private void PopulateForm ( )
        {
            imgPicture.ImageUrl = User.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";
            lblEmail.HRef = string.Format ( "mailto:{0}", User.Email );
            lblEmail.InnerText = SPHelpers.ConvertHtmlToKiiroSafeText ( User.Email );
            lblIM.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.IM );
            lblIMClient.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.IMClient );
            lnkFullName.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.FullName );
            lblTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.Title );
            lnkFullName.NavigateUrl = String.Format ( "{0}/DisplayUser.aspx?id={1}", ServerRelativeUrl, User.SPUserId );

            lblPhoneNumber.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.PhoneNumber );
            lblDescription.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( User.Description );
        }

        private void PopulateProjectsListing ( )
        {
            //use full name because first name comes as null if not entered since it is not required
            lblPersonsProjects.InnerText = string.Format ( "{0}'s Projects", SPHelpers.ConvertHtmlToKiiroSafeText ( User.FullName ) );

            // The list of projects that the current user can see.
            List<Project> projects = ProjectsModel.GetProjectsForUser (
                SiteCollectionId,
                ServerRelativeUrl,
                CurrentUser,
                new List<ProjectStatus> ( ) { ProjectStatus.Active, ProjectStatus.BeingPlanned } );

            // An Administrator can see all projects but we only want to show projects that they are assigned to.
            //      remove all projects from the list that displayed user is not part of. 
            projects.RemoveAll ( project => !User.ProjectIds.Contains ( project.Id ) );

            double today = default ( double );
            double shouldBe = default ( double );

            if ( projects != null && projects.Count > 0 )
            {
                pnlProjectsList.Visible = true;

                foreach ( Project project in projects )
                {
                    string cssClass = projects.IndexOf ( project ) == projects.Count - 1 ? "borderless" : "";

                    today = Math.Round ( ( project.ActualWork / project.TotalWork ) * 100, 0 );
                    today = !Double.IsNaN ( today ) && !Double.IsInfinity ( today ) ? today : 0;

                    shouldBe = Math.Round ( ( project.ProjectedWork / project.TotalWork ) * 100, 0 );
                    shouldBe = !Double.IsNaN ( shouldBe ) && !Double.IsInfinity ( shouldBe ) ? shouldBe : 0;

                    string image = "<img src='{0}' alt='{1}' />";
                    if ( ( shouldBe - today ) < 10 )
                        image = string.Format ( image, "/_layouts/images/Kiiro/good.png", "good" );
                    else if ( ( shouldBe - today ) < 30 && ( shouldBe - today ) >= 10 )
                        image = string.Format ( image, "/_layouts/images/Kiiro/bad.png", "bad" );
                    else
                        image = string.Format ( image, "/_layouts/images/Kiiro/ugly.png", "ugly" );

                    string estimatedEndDate = string.Empty;
                    if ( project.StartDate != DateTime.MinValue && project.EndDate != DateTime.MinValue )
                    {

                        int totalWorkDays = DateTimeHelpers.GetNumberOfWorkDays ( project.StartDate, project.EndDate );
                        int currentWorkDays = ( int ) ( ( totalWorkDays * ( today == 0 ? 1 : today ) ) / 100 );
                        int sbDays = ( int ) ( ( totalWorkDays * shouldBe ) / 100 );
                        int totalEstimatedDays = ( sbDays * totalWorkDays ) / ( currentWorkDays == 0 ? 1 : currentWorkDays );
                        int remainingWorkDays = totalEstimatedDays - currentWorkDays;
                        remainingWorkDays--; // account for today

                    }

                    litProjectsList.Text += @"<li class='" + cssClass + @"'>
                        <div class='title'>
                          <a href='" + project.ServerRelativeWebUrl + @"'><h2>" + SPHelpers.ConvertHtmlToKiiroSafeText ( project.Title ) + @"</h2></a>
                        </div>
                        <div class='timeline'>
                            <div class='progress'>" +
                                image +
                                @"<div id='progressGutter' runat='server' class='progress-gutter'>
                                    <div id='progressBar' runat='server' class='progress-bar' style='width:" + 234 * ( today / 100 ) + @"px'></div>
                                </div>
                                <h2>" + string.Format ( "{0}%", today.ToString ( ) ) + @"</h2> 
                            </div>
                        </div>
                        <div class='start'>" + FormattingHelpers.DateTimeToStringOrDashes(project.StartDate) + @"</div>
                        <div class='end'>" + FormattingHelpers.DateTimeToStringOrDashes ( project.EndDate ) + @"</div>
                    </li>";
                }
            }
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.User/User/DisplayUser.aspx.cs $
 * 
 * 33    2/08/10 5:04p Camerons
 * 
 * 32    2/08/10 2:28p Camerons
 * 
 * 31    1/25/10 1:17p Camerons
 * 
 * 30    1/12/10 12:03p Camerons
 * 
 * 29    1/07/10 12:28p Camerons
 * 
 * 28    1/06/10 12:39p Camerons
 * 
 * 27    12/23/09 3:31p Stefanf
 * 
 * 26    2/12/09 1:26p Shafia
 * 
 * 25    26/11/09 10:35a Camerons
 * 
 * 24    17/11/09 6:46p Camerons
 * 
 * 23    6/11/09 7:34p Camerons
 * 
 * 22    31/10/09 2:59p Camerons
 * 
 * 21    31/10/09 11:58a Camerons
 * 
 * 20    30/10/09 12:54p Camerons
 * 
 * 19    10/26/09 9:31a Adamw
 * Case 348
 * 
 * 18    8/10/09 3:27p Camerons
 * 
 * 17    7/10/09 2:57p Camerons
 * 
 * 16    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 15    30/09/09 2:03p Camerons
 * 
 * 14    30/09/09 1:08p Camerons
 * Implementing UserModel.GetOrCreateUser(). 
 * 
 * 13    30/09/09 10:00a Shafia
 * 
 * 12    23/09/09 1:02p Camerons
 * Hide status update if user cannot update themself
 * 
 * 11    21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 10    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/